package com.liu.spider.controller;

import cn.hutool.json.JSON;
import com.liu.spider.entity.Task;
import com.liu.spider.enums.TaskStatus;
import com.liu.spider.service.ITaskService;
import com.liu.spider.system.dto.output.ApiResult;
import com.liu.spider.task.CronTaskRegistrar;
import com.liu.spider.task.SchedulingRunnable;
import io.github.chenxuancode.base.enums.ResultCode;
import io.github.chenxuancode.base.vo.ResultVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * @author Nicky
 * @version 1.0
 * @className TaskController
 * @blog goitman.cn | blog.csdn.net/minkeyto
 * @description 控制层类
 * @date 2020/10/28 16:41
 */
@RestController
@Validated
@Api(tags = "定时任务调用接口")
public class TaskController {

    @Autowired
    private ITaskService taskService;

    @Autowired
    private CronTaskRegistrar cronTaskRegistrar;

    /**
     * 添加任务
     */
    @PostMapping("/addTask")
    @ApiOperation(value = "添加定时任务", httpMethod = "POST", response = ApiResult.class, notes = "添加定时任务")
    public ApiResult addTask(@Valid @RequestBody Task task) {
        if (taskService.insertTask(task) <= 0) {
            return ApiResult.fail("新增失败！");
        } else {
            if (task.getJobStatus().equals(TaskStatus.NORMAL.value())) {
                SchedulingRunnable runnable = new SchedulingRunnable(task.getBeanName(), task.getMethodName(), task.getMethodParams());
                cronTaskRegistrar.addCronTask(runnable, task.getCronExpression());
            }
        }
        return ApiResult.ok("新增成功！");
    }

    /**
     * 删除任务
     */
    @DeleteMapping("/deleteTask/{id}")
    @ApiOperation(value = "删除定时任务", httpMethod = "DELETE", response = ApiResult.class, notes = "删除定时任务")
    public ApiResult deleteTask(@PathVariable Long id) {
        Task task = taskService.findTaskByJobId(id);
        if (!taskService.deleteTaskByJobId(id)) {
            return ApiResult.fail("删除失败！");
        } else {
            if (task.getJobStatus().equals(TaskStatus.NORMAL.value())) {
                SchedulingRunnable runnable = new SchedulingRunnable(task.getBeanName(), task.getMethodName(), task.getMethodParams());
                cronTaskRegistrar.removeCronTask(runnable);
            }
        }
        return ApiResult.ok("删除成功！");
    }

    /**
     * 修改任务
     */
    @PostMapping("/updateTask")
    @ApiOperation(value = "修改定时任务", httpMethod = "POST", response = ApiResult.class, notes = "修改定时任务")
    public ApiResult updateTask(@RequestBody Task taskNew) {
        Task taskOld = taskService.findTaskByJobId(taskNew.getId());
        if (taskService.updateTask(taskNew)) {
            // 先取消原有的定时任务，并删除缓存
            if (taskOld.getJobStatus().equals(TaskStatus.NORMAL.value())) {
                // 链式编程，使用了lombok的注解@Accessors
                SchedulingRunnable runnable = new SchedulingRunnable()
                        .setBeanName(taskOld.getBeanName())
                        .setMethodName(taskOld.getMethodName())
                        .setParams(taskOld.getMethodParams());
                cronTaskRegistrar.removeCronTask(runnable);
            }else return ApiResult.ok("更新成功！");
            // 新增定时任务，并添加到缓存
            if (taskNew.getJobStatus().equals(TaskStatus.NORMAL.value())) {
                SchedulingRunnable runnable = new SchedulingRunnable(taskNew.getBeanName(), taskNew.getMethodName(), taskNew.getMethodParams());
                cronTaskRegistrar.addCronTask(runnable, taskNew.getCronExpression());
            }
        } else {
            return ApiResult.fail("更新失败！");
        }
        return ApiResult.ok("更新成功！");
    }

    /**
     * 切换任务状态
     */
    @GetMapping("/switchTaskStatus/{id}")
    @ApiOperation(value = "切换任务状态", httpMethod = "GET", response = ApiResult.class, notes = "切换任务状态")
    public ApiResult switchTaskStatus(@PathVariable Long id) {
        Task task = taskService.findTaskByJobId(id);
        // 如原先是启动状态，便设置为停止，并从缓存中删除，反之亦然
        if (task.getJobStatus().equals(TaskStatus.NORMAL.value())) {
            SchedulingRunnable runnable = new SchedulingRunnable(task.getBeanName(), task.getMethodName(), task.getMethodParams());
            cronTaskRegistrar.removeCronTask(runnable);
            task.setJobStatus(TaskStatus.SUSPEND.value());
            return taskService.updateTask(task) ? ApiResult.ok("修改成功！") :ApiResult.fail("修改失败！");
        } else {
            SchedulingRunnable runnable = new SchedulingRunnable(task.getBeanName(), task.getMethodName(), task.getMethodParams());
            cronTaskRegistrar.addCronTask(runnable, task.getCronExpression());
            task.setJobStatus(TaskStatus.NORMAL.value());
            return taskService.updateTask(task) ? ApiResult.ok("修改成功！") : ApiResult.fail("修改失败！");
        }
    }

    @GetMapping("/list/{page}")
    @ApiOperation(value = "查看当前定时任务列表", httpMethod = "GET", response = ApiResult.class, notes = "查看当前定时任务列表")
    public ApiResult getPage(@PathVariable Integer page) {
        return new ApiResult(taskService.getTaskList(page));
    }

}